import pygame,sys,random
import set,class_set
from pygame.locals import *
from config_set import CONFIG

class Game():
    #初始化
    def __init__(self):
        set.load_dir()
        self.screen,self.background= set.game_init()
        self.background_list()
        self.sprite_init()
        self.main_menu = self.creat_main_menu()
        self.game_over_menu = self.creat_game_over_menu()
        self.enemy_spawn_timer = class_set.Timer(1000)#敌人生成定时器
        self.score_timer = class_set.Timer(10)
        self.run = True
        self.game_case = 'main_menu'
        self.score_list=[0]
        self.score=0
    #初始化所有对象
    def sprite_init(self):
        self.all_sprites = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.player_group = pygame.sprite.Group()
        self.player_bullets = pygame.sprite.Group()
        self.enemy_bullets = pygame.sprite.Group()
        self.all_sprites.add(self.enemies)
    #创建玩家
    def create_player(self):
        self.player = class_set.Player((400,300),CONFIG['player'],set_size=True,size=(50,50),bullet_group=self.player_bullets,all_sprites=self.all_sprites)
        self.player_group.add(self.player)
        self.all_sprites.add(self.player)
    #加载背景列表
    def background_list(self):
        self.backgrounds={
            'main_menu':set.load_background('main_menu'),
            'playing':set.load_background('playing'),
            'game_over':set.load_background('game_over'),
        }
    #设置主菜单
    def creat_main_menu(self):
        menu = class_set.Menu(self.screen)
        
        start_btn = class_set.Button(CONFIG['start'],
                                     CONFIG['confirm'],
                                     (400,100),
                                     self.begin_game,
                                     True,
                                     (100,100),)
        exit_btn = class_set.Button(CONFIG['exit'],
                                     CONFIG['confirm'],
                                     (400,300),
                                     self.exit_game,
                                     True,
                                     (100,100),)
        menu.add_button(start_btn)
        menu.add_button(exit_btn)
        return menu
    #创建结束界面:
    def creat_game_over_menu(self):
        menu = class_set.Menu(self.screen)
        #创建按钮
        reset_btn = class_set.Button(CONFIG['reset'],
                                     CONFIG['confirm'],
                                     (400,100),
                                     self.begin_game,
                                     True,
                                     (100,100),)
        exit_btn = class_set.Button(CONFIG['exit'],
                                     CONFIG['confirm'],
                                     (400,300),
                                     self.exit_game,
                                     True,
                                     (100,100),)
        menu.add_button(reset_btn)
        menu.add_button(exit_btn)
        return menu
       #让状态改为开始
    def begin_game(self):
        #清空所有精灵
         self.all_sprites.empty()
         self.enemies.empty()
         self.player_bullets.empty()
         self.enemy_bullets.empty()
         self.player_group.empty()
         #创建玩家
         self.create_player()
         #记录最高分数
         self.max_score = max(self.score_list)
         self.game_case = 'playing'
        #让状态改为玩家死亡
    def player_death(self):
        self.game_case = 'game_over'
    #让状态改为结束
    def exit_game(self):
        self.run = False
        # 处理事件
    def handle_event(self,events):
        self.run =set.handle_exit(self.run,events)
    #处理游戏中的事件
    def playing_handle(self):
        if self.player.hp <= 0:
            self.player_death()
        self.handle_score()
        self.check_collision()
        self.show_hp(self.screen)
        if self.enemy_spawn_timer.is_seted():
            self.spawn_enemy()
        self.all_sprites.update()
        self.all_sprites.draw(self.screen)
    #敌人绘制
    def spawn_enemy(self):
        x = random.randint(0,CONFIG['screen_size'][0])
        y = -50
        enemy = class_set.Enemy((x,y),CONFIG['enemy'],set_size=True,size=(50,50),bullet_group= self.enemy_bullets,all_sprites=self.all_sprites,on_death= lambda:self.add_score(500))
        self.enemies.add(enemy)
        self.all_sprites.add(enemy)
    #展示血条：
    def show_hp(self,surface):
        #绘制玩家血条
        player_hp_width = self.player.rect.width * self.player.hp / self.player.max_hp
        player_hp_bar_y = self.player.rect.y - 10
        pygame.draw.rect(surface,(255,0,0),(self.player.rect.x,player_hp_bar_y,self.player.rect.width,10))
        pygame.draw.rect(surface,(0,255,0),(self.player.rect.x,player_hp_bar_y,player_hp_width,10))
        #绘制敌人血条
        for enemy in self.enemies:
           hp_width = enemy.rect.width * enemy.hp / enemy.max_hp
           hp_bar_y = enemy.rect.y - 10
           pygame.draw.rect(surface,(255,0,0),(enemy.rect.x,hp_bar_y,enemy.rect.width,enemy.hp_bar))
           pygame.draw.rect(surface,(0,255,0),(enemy.rect.x,hp_bar_y,hp_width,enemy.hp_bar))
    #检查碰撞
    def check_collision(self):
        #玩家子弹和敌人
        player_bullet_collisions = pygame.sprite.groupcollide(self.enemies,self.player_bullets,False,True)
        for enemy,bullets in player_bullet_collisions.items():
            for bullet in bullets:
                enemy.take_damage(bullet.damage)
                self.add_score(100)
         #敌人子弹和玩家
        enemy_bullet_collisions = pygame.sprite.groupcollide(self.player_group,self.enemy_bullets,False,True)
        for player,bullets in enemy_bullet_collisions.items():
            for bullet in bullets:
                player.take_damage(bullet.damage)
        #敌人和玩家
        enemy_collisions = pygame.sprite.groupcollide(self.enemies,self.player_group,True,False)
        for enemy,players in enemy_collisions.items():
            for player in players:
                player.take_damage(enemy.damage)
        
            
    #更新屏幕
    def update_screen(self):
        self.screen.blit(self.backgrounds[self.game_case],(0,0))
        

    #更新页面
    def update_case(self,events):
        if self.game_case == 'main_menu':
            self.main_menu.handle_event(events)
            self.main_menu.draw()
        elif self.game_case == 'playing':
            self.playing_handle()
        elif self.game_case == 'game_over':
            self.game_over_menu.handle_event(events)
            self.game_over_menu.draw()
    #增加积分
    def add_score(self,score):
        self.score += score
    #处理分数
    def handle_score(self):
        if self.game_case == 'playing':
            set.draw_text(f'分数:{self.score}',CONFIG['font1'],55,(255,255,255),self.screen,370,20)
            set.draw_text(f'历史最高分数:{self.max_score}',CONFIG['font1'],55,(255,255,255),self.screen,330,80)
        elif self.game_case == 'game_over'or'main_menu':
            if self.score != 0:
                self.score_list.append(self.score)
                self.score = 0
                
        
    #游戏运行
    def run_game(self):
        clock = pygame.time.Clock()
        while self.run:
            clock.tick(60)
            events = pygame.event.get()
            self.handle_event(events)
            self.update_screen()
            self.update_case(events)
            pygame.display.flip()
        pygame.quit()
        sys.exit()
               

if __name__ == '__main__':
    game = Game()
    game.run_game()